#include "ringbuffer.h"
#include <stdlib.h>

void rb_init(ringbuffer *rb, rbdata *buffer, rbsize size)
{
	rb->head = rb->tail = 0;

	rb->buffer = buffer;
	rb->size = size;
}

void rb_push(ringbuffer *rb, rbdata d)
{
	rbsize pos = (rb->head + 1) % rb->size;
	if (pos != rb->tail)
	{
		rb->buffer[rb->head] = d;
		rb->head = pos;
	}
}

void rb_pop(ringbuffer *rb, rbdata *d)
{
	if (rb->tail != rb->head) //非空状态
	{
		*d = rb->buffer[rb->tail];
		rb->tail = (rb->tail + 1) % rb->size;
	}
}

rbsize rb_size(ringbuffer *rb)
{
	return ((rb->head + rb->size - rb->tail) % rb->size);
}

int rb_test()
{
#define SIZE 10
	ringbuffer rb;
	rbdata *buffer = malloc(sizeof(rbdata) * SIZE);
	if (buffer == NULL)
		return -1;
	rb_init(&rb, buffer, SIZE);
	for (int i = 0; i < SIZE - 1; i++)
	{
		rb_push(&rb, (rbdata)i);
		// printf("---%d\r\n", i);
	}
	while (rb_size(&rb))
	{
		rbdata d;
		rb_pop(&rb, &d);
		printf("%d\r\n", d);
	}
	return 0;
}
